import Cookies from "js-cookie";
import request from "@/utils/request";
import { Toast } from "mint-ui";
import { Notification, MessageBox, Message } from "element-ui";
const TokenKey = "Admin-Token";
import { server } from "@/utils/env";

export function getToken() {
  return Cookies.get(TokenKey);
}

export function setToken(token) {
  console.log(token,'token')
  return Cookies.set(TokenKey, token);
}
export function delToken() {
  return Cookies.set(TokenKey, "", -1);
}
export function removeToken() {
  return Cookies.remove(TokenKey);
}

const getUrlCode = () => {
  // 截取url中的code方法
  var url = location.search;
  var theRequest = new Object();
  console.log(url, url.indexOf("?"));
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  return theRequest;
};
export const getCode = () => {
  console.log('走这里')
  if (getToken()) {
    // 来自分享增加积分
    if (getUrlCode().userId != null) {
      console.log("来自分享增加积分");
      return request({
        url: "/generator/userpoints/front/getpoints",
        method: "get",
        params: {
          shareUserId: getUrlCode().userId,
        },
      });
    }
  } else {
    // 非静默授权，第一次有弹框
    let code = "";
    var local = window.location.href; // 获取页面url
    var appid = server.appId;
    code = getUrlCode().code; // 截取code
    if (code == null || code === "") {
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
        local
      )}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
    } else {
      console.log("登录");
      let userId = window.localStorage.getItem("userId");
      let state = userId ? 0 : getUrlCode().shareUserId;
      return request({
        url: "/generator/user/front/wxlogin",
        method: "post",
        data: {
          jscode: code,
          state: state || 0,
        },
      }).then((response) => {
        setToken(response.token);
        console.log(response, "response");
        window.localStorage.setItem("userId", response.user.id);
        if (response.state == 0 && getUrlCode().shareUserId) {
          window.sessionStorage.setItem("first", 0);
        } else {
          window.sessionStorage.setItem("first", 1);
        }
      });
    }
  }
};
export const registerDay = () => {
  return request({
    url: "/generator/user/front/register",
    method: "get",
  }).then((response) => {
    if (response.status == 0) {
      Toast({
        message: response.message,
        iconClass: "glyphicon glyphicon-ok",
      });
    }
  });
};
